package com.kgc.service.Impl.admin;

import com.kgc.dao.mapper.admin.AdminMapper;
import com.kgc.dao.mapper.admin.AdminRoleMapper;
import com.kgc.entity.Role;
import com.kgc.entity.User;
import com.kgc.service.interf.admin.AdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hyj
 * @time 2024/4/6 14:20
 * @describe
 */
@Service("adminRoleService")
public class AdminRoleServiceImpl implements AdminRoleService {
    @Autowired
    private AdminRoleMapper adminRoleMapper;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Integer insertRole(String roleName) {
        return adminRoleMapper.insertRole(roleName);
    }

    @Override
    public Integer insertUserAndRole(Integer userId, Integer roleId) {
        return adminRoleMapper.insertUserAndRole(userId, roleId);
    }

    @Override
    public Integer deleteUserAndRole(Integer userId, Integer roleId) {
        return adminRoleMapper.deleteUserAndRole(userId);
    }

    @Override
    public Integer updateUserAndRole(Integer userId, Integer roleId) {
        return adminRoleMapper.updateUserAndRole(userId, roleId);
    }

    @Override
    public List<User> getAll() {
        List<User> allRoles = new ArrayList<>();
        List<User> allUser = adminMapper.getAllUser();
        for (User user : allUser) {
            List<Role> roles = adminRoleMapper.rolesByUserId(user.getUserId());
            int size = roles.size();
            if (size == 1) {
                user.setRoleId(roles.get(0).getRoleId());
                user.setRoleName(roles.get(0).getRoleName());
            } else if (size > 1) {
                Integer[] roleIds = new Integer[size];
                String[] roleNames = new String[size];
                for (int i = 0; i < size; i++) {
                    roleIds[i] = roles.get(i).getRoleId();
                    roleNames[i] = roles.get(i).getRoleName();
                }
                user.setRoleIds(roleIds);
                user.setRoleNames(roleNames);
            }
            allRoles.add(user);
        }
        return allRoles;
    }

    @Override
    public List<Role> roles() {
        return adminRoleMapper.roles();
    }

    @Override
    public String updateRole(Integer userId, Integer[] roleIds) {
        int count = 0;
        adminRoleMapper.deleteUserAndRole(userId);
        for (Integer roleId : roleIds) {
            Integer i = adminRoleMapper.insertUserAndRole(userId, roleId);
            if (i == 1) {
                count++;
            }
        }
        if (count == roleIds.length) {
            return "更新成功";
        }
        return "更新失败";
    }
}
